package com.xinjian.jianba.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.xinjian.jianba.dao.dwmid.BuziInfoDao;
import com.xinjian.jianba.dao.dwmid.RyGroupDao;
import com.xinjian.jianba.dao.dwmid.RyGroupInfoDao;
import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.dao.dwmid.UserVisitBuziDao;
import com.xinjian.jianba.dto.GroupDetailVo;
import com.xinjian.jianba.dto.GroupIdDto;
import com.xinjian.jianba.dto.GroupMembersVo;
import com.xinjian.jianba.dto.GroupUserVo;
import com.xinjian.jianba.dto.GroupsVo;
import com.xinjian.jianba.dto.JoinGroupDto;
import com.xinjian.jianba.dto.QuitGroupDto;
import com.xinjian.jianba.dto.UserTrackBuziNamesDto;
import com.xinjian.jianba.dto.UserTrackBuziNamesUsersVo;
import com.xinjian.jianba.dto.UserTrackBuziNamesVo;
import com.xinjian.jianba.dto.UserTrackBuziUsersDto;
import com.xinjian.jianba.enity.BuziInfoEntity;
import com.xinjian.jianba.enity.RyGroupEntity;
import com.xinjian.jianba.enity.RyGroupInfoEntity;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.enity.UserVisitBuziEntity;
import com.xinjian.jianba.exception.BusinessException;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.exception.ResponseCodeAwareException;
import com.xinjian.jianba.service.RongYunGroupService;
import com.xinjian.jianba.util.rongyungroup.GroupUtil;
import com.xinjian.jianba.utils.DateUtil;

import io.rong.models.Result;
@Service
public class RongYunGroupServiceImpl implements RongYunGroupService{
	private static final Logger log = LoggerFactory
			.getLogger(RongYunGroupServiceImpl.class);
	@Autowired
	private RyGroupDao ryGroupDao;
	@Autowired
	private RyGroupInfoDao ryGroupInfoDao;
	public final static String groupName="群组";
	public final static String buziname="xxx";
	@Value("${jianba.business.buziLogo}")
	private String buziLogo;
	@Value("${jianba.qiniu.female}")
	private String female;
	@Value("${jianba.qiniu.male}")
	private String male;
	@Value("${jianba.business.grouplogo}")
	private String groupLogo;
	@Autowired
	private UserVisitBuziDao userVisitBuziDao;
	@Autowired
	private UserInfoDao userInfoDao;
	@Autowired
	private BuziInfoDao buziInfoDao;
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void joinGroup(JoinGroupDto joinGroupDto) {
		Date date=new Date();
		//校验群成员id
		GroupUtil.checkInfoids(joinGroupDto.getInfoIds());
		//查询群是否存在
		List<RyGroupEntity> list=ryGroupDao.selectByGroupId(joinGroupDto.getGroupId());
		if(CollectionUtils.isEmpty(list)){
			throw new BusinessException(ResponseCode.ERROR, "该群不存在");
		}
		String groupName=list.get(0).getGroupName();
		//插入群成员
		List<RyGroupInfoEntity> ryList=new ArrayList<RyGroupInfoEntity>();
		String[] infoIds=joinGroupDto.getInfoIds();
		for(int i=0;i<infoIds.length;i++){
			int infoType=0;
			if(infoIds[i].lastIndexOf("b")>0){
				infoType=1;
			}
			RyGroupInfoEntity ryGroupInfoEntity=new RyGroupInfoEntity();
			ryGroupInfoEntity.setAddDate(date);
			ryGroupInfoEntity.setAddTime(date);
			ryGroupInfoEntity.setGroupId(joinGroupDto.getGroupId());
			ryGroupInfoEntity.setGroupName(groupName);
			ryGroupInfoEntity.setInfoId(Long.parseLong(infoIds[i].trim().substring(0, infoIds[i].length()-1)));
			ryGroupInfoEntity.setInfoType(infoType);
			ryGroupInfoEntity.setRyInfoId(infoIds[i]);
			ryGroupInfoEntity.setType(2);
			ryList.add(ryGroupInfoEntity);
		}
		try{
			ryGroupInfoDao.insertByBatch(ryList);
		}catch(DuplicateKeyException e){
			log.info("joinGroup-------错误{}",e);
			throw new ResponseCodeAwareException(200, "不能重复添加已入群的人员,请核实");
		}
		GroupUtil.joinGroup(infoIds, joinGroupDto.getGroupId(), groupName);
	}
	@Override
	public void inviteGroup(JoinGroupDto joinGroupDto) {
		Date date=new Date();
		//校验群成员id
		GroupUtil.checkInfoids(joinGroupDto.getInfoIds());
		//查询群是否存在
		List<RyGroupEntity> list=ryGroupDao.selectByGroupId(joinGroupDto.getGroupId());
		if(CollectionUtils.isEmpty(list)){
			throw new BusinessException(ResponseCode.ERROR, "该群不存在");
		}
		String groupName=list.get(0).getGroupName();
		//插入群成员
		List<RyGroupInfoEntity> ryList=new ArrayList<RyGroupInfoEntity>();
		String[] infoIds=joinGroupDto.getInfoIds();
		for(int i=0;i<infoIds.length;i++){
			int infoType=0;
			if(infoIds[i].lastIndexOf("b")>0){
				infoType=1;
			}
			RyGroupInfoEntity ryGroupInfoEntity=new RyGroupInfoEntity();
			ryGroupInfoEntity.setAddDate(date);
			ryGroupInfoEntity.setAddTime(date);
			ryGroupInfoEntity.setGroupId(joinGroupDto.getGroupId());
			ryGroupInfoEntity.setGroupName(groupName);
			ryGroupInfoEntity.setInfoId(Long.parseLong(infoIds[i].trim().substring(0, infoIds[i].length()-1)));
			ryGroupInfoEntity.setInfoType(infoType);
			ryGroupInfoEntity.setRyInfoId(infoIds[i]);
			ryGroupInfoEntity.setType(2);
			ryList.add(ryGroupInfoEntity);
		}
		try{
			ryGroupInfoDao.insertByBatch(ryList);
		}catch(DuplicateKeyException e){
			log.info("joinGroup-------错误{}",e);
			throw new BusinessException(ResponseCode.ERROR, "不能重复添加已入群的人员,请核实");
		}
		GroupUtil.inviteGroup(joinGroupDto.getInfoIds(), joinGroupDto.getGroupId(), joinGroupDto.getGroupName());
		
	}
	@Override
	public GroupMembersVo getGroupInfos(GroupIdDto groupIdDto) {
		String  groupName=null;
		List<RyGroupInfoEntity> list=ryGroupInfoDao.selectPageByGroupId(groupIdDto);
		//查询群成员总人数
		Map<String, String> map=ryGroupInfoDao.selectGroupCounts(groupIdDto.getGroupId());
		String count=String.valueOf(map.get("num"));
		String title=map.get("title")==null?"":map.get("title").toString();
		
		if(!CollectionUtils.isEmpty(list)){
			groupName=list.get(0).getGroupName();
		}
		List<Long> userIdList=new ArrayList<Long>();
		List<Long> buziIdList=new ArrayList<Long>();
		list.stream().forEach(ryGroupInfoEntity->{
			if(ryGroupInfoEntity.getInfoType()==0){
				userIdList.add(ryGroupInfoEntity.getInfoId());
			}else{
				buziIdList.add(ryGroupInfoEntity.getInfoId());
			}
		});
		Map<Long,UserInfoEnity> userMap=null;
		Map<Long,BuziInfoEntity> buziMap=null;
		if(!CollectionUtils.isEmpty(userIdList)){
			 userMap=userInfoDao.findByUserIdListGroup(userIdList);
		}
		if(!CollectionUtils.isEmpty(buziIdList)){
			 buziMap=buziInfoDao.findByBuziIdList(buziIdList);
		}
		Map<Long,UserInfoEnity> userReMap=userMap;
		Map<Long,BuziInfoEntity> buziReMap=buziMap;
		List<GroupUserVo> reList=new ArrayList<GroupUserVo>();
		list.stream().forEach(ryGroupInfo->{
			String name=null;
			String logo=null;
			int infotype=ryGroupInfo.getInfoType();
			if(infotype==0){//用户
				UserInfoEnity userInfo=userReMap.get(ryGroupInfo.getInfoId());
				name=userInfo.getNickname();
				logo=userInfo.getUserLogo();
				int sex=userInfo.getSex();
				if(logo==null&&sex==0){
					logo=male;
				}
				if(logo==null&&sex==1){
					logo=female;
				}
			}else {//商家
				BuziInfoEntity buziInfo=buziReMap.get(ryGroupInfo.getInfoId());
				name=buziInfo.getName()==null?buziname:buziInfo.getName();
				logo=buziInfo.getLogo()==null?buziLogo:buziInfo.getLogo();
			}
			GroupUserVo groupUserVo=new GroupUserVo();
			groupUserVo.setInfoId(ryGroupInfo.getInfoId());
			groupUserVo.setInfoType(ryGroupInfo.getInfoType());
			groupUserVo.setLogo(logo);
			groupUserVo.setName(name);
			groupUserVo.setRyInfoId(ryGroupInfo.getRyInfoId());
			groupUserVo.setType(ryGroupInfo.getType());
			reList.add(groupUserVo);
		});
		
		GroupMembersVo groupMembersVo=new GroupMembersVo();
		groupMembersVo.setGroupId(groupIdDto.getGroupId());
		groupMembersVo.setGroupName(groupName);
		groupMembersVo.setTitle(title);
		groupMembersVo.setTotalCounts(count);
		groupMembersVo.setMembers(reList);
		
		return groupMembersVo;
	}
	@Override
	@Transactional(rollbackFor=Exception.class)
	public Result quitGroup(QuitGroupDto quitGroupDto) {
		GroupUtil.checkInfoid(quitGroupDto.getInfoId());
		int count=ryGroupInfoDao.quitGroupMembers(quitGroupDto);
		if(count!=1){
			throw new BusinessException(ResponseCode.ERROR,"不能移除群主");
		}
		io.rong.models.Result ryResult=GroupUtil.quitGroup(new String[]{quitGroupDto.getInfoId()}, quitGroupDto.getGroupId(), quitGroupDto.getGroupName());
		return ryResult;
	}
	@Override
	public List<GroupsVo> groupsWithMe(String userId) {
		List<GroupsVo> listRe=ryGroupDao.findGroups(userId+"a");
		listRe.stream().forEach(groupVo->{
			groupVo.setGroupLogo(groupVo.getGroupLogo()==null?groupLogo:groupVo.getGroupLogo());
			groupVo.setGroupName(groupVo.getGroupName()==null?groupName:groupVo.getGroupName());
		});
		return listRe;
	}
	@Override
	public GroupDetailVo groupDetail(String groupId) {
		GroupDetailVo groupDetailVo=ryGroupDao.groupDetail(groupId);
		groupDetailVo.setGroupLogo(groupDetailVo.getGroupLogo()==null?groupLogo:groupDetailVo.getGroupLogo());
		groupDetailVo.setGroupName(groupDetailVo.getGroupName()==null?groupName:groupDetailVo.getGroupName());
		return groupDetailVo;
	}
	@Override
	public List<UserTrackBuziNamesVo> trackBuziNames(UserTrackBuziNamesDto userTrackBuziNamesDto) {
		List<UserVisitBuziEntity> list=userVisitBuziDao.findUserTrackBuziNames(userTrackBuziNamesDto);
		List<UserTrackBuziNamesVo> listReVo=new ArrayList<UserTrackBuziNamesVo>();
		list.stream().forEach(userVisitBuziEntity->{
			UserTrackBuziNamesVo userTrackBuziNamesVo=new UserTrackBuziNamesVo();
			String buziName=userVisitBuziEntity.getBuziInfoEntity().getName();
			buziName=buziName==null?buziname:buziName;
			userTrackBuziNamesVo.setBuziName(buziName);
			userTrackBuziNamesVo.setBuziId(String.valueOf(userVisitBuziEntity.getBuziid()));
			userTrackBuziNamesVo.setLastTime(DateUtil.utilDateToTimestampString(userVisitBuziEntity.getUpTime()));
			//获取6个去过该店铺的人
			UserTrackBuziUsersDto userTrackBuziUsersDto=new UserTrackBuziUsersDto();
			userTrackBuziUsersDto.setBuziId(userTrackBuziNamesVo.getBuziId());
			userTrackBuziUsersDto.setPageNumber(1);
			userTrackBuziUsersDto.setPageSize(6);
			List<UserTrackBuziNamesUsersVo> listuserVo=buziNameTrackUsers(userTrackBuziUsersDto);
			userTrackBuziNamesVo.setList(listuserVo);
			listReVo.add(userTrackBuziNamesVo);
		});
		
		
		return listReVo;
	}
	@Override
	public List<UserTrackBuziNamesUsersVo> buziNameTrackUsers(UserTrackBuziUsersDto userTrackBuziUsersDto) {
		List<UserTrackBuziNamesUsersVo> listuserVo=new ArrayList<UserTrackBuziNamesUsersVo>(); 
		List<UserVisitBuziEntity> list=userVisitBuziDao.findUserTrackUsers(userTrackBuziUsersDto);
		list.stream().forEach(userVisitBuzi->{
			UserTrackBuziNamesUsersVo usersVo=new UserTrackBuziNamesUsersVo();
			usersVo.setUserId(String.valueOf(userVisitBuzi.getUserId()));
			String userLogo=userVisitBuzi.getUserInfoEnity().getUserLogo();
			int sex=userVisitBuzi.getUserInfoEnity().getSex();
			if(userLogo==null&&sex==0){
				userLogo=male;
			}
			if(userLogo==null&&sex==1){
				userLogo=female;
			}
			usersVo.setUserLogo(userLogo);
			usersVo.setLastTime(DateUtil.utilDateToTimestampString(userVisitBuzi.getUpTime()));
			usersVo.setUserName(userVisitBuzi.getUserInfoEnity().getNickname());
			listuserVo.add(usersVo);
		});
		return listuserVo;
	}

}
